﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace SharpSoft.Web
{
    /// <summary>
    /// 扩展默认的权限认证
    /// </summary>
    public class AuthorizationService : DefaultAuthorizationService, IAuthorizationService
    {
        public AuthorizationService(IAuthorizationPolicyProvider policyProvider, IAuthorizationHandlerProvider handlers, ILogger<DefaultAuthorizationService> logger, IAuthorizationHandlerContextFactory contextFactory, IAuthorizationEvaluator evaluator, IOptions<AuthorizationOptions> options) : base(policyProvider, handlers, logger, contextFactory, evaluator, options)
        {

        }
        /// <summary>
        /// 系统的认证架构
        /// </summary>
        public static string DefaultAuthenticationScheme = "DEF_AUTH";
        /// <summary>
        /// 根账号的claim类型
        /// </summary>
        public const string RootUserClaimType = "isrootuser";

        public new async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
        {
            if (user.HasClaim(p => p.Type == AuthorizationService.RootUserClaimType && p.Value == "True"))
            {//系统根账号跳过所有权限认证
                return AuthorizationResult.Success();
            } 
            return await base.AuthorizeAsync(user, resource, requirements);
        }

        public new async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
        {
            return await base.AuthorizeAsync(user, resource, policyName);
        }
    }
}
